package com.da.lon.wang.xlg.adapter;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.ResultSearchBean.ResultSearchListBean.SearchResultCategory;
import com.da.lon.wang.xlg.bean.ResultSearchBean.ResultSearchListBean.SearchResultOther;
import com.da.lon.wang.xlg.bean.ResultSearchBean.ResultSearchListBean.SearchResultOther.SearchResultOtherItems;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.ToastUtils;

import java.util.ArrayList;

public class FilterAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private Context context = null;
    private int type = 1;

    private String attr = PreferenceUtils.getInstance().getSettingStr(
            PreferencesConfig.SEARCH_SATTR, "");
    protected int touchedPosition = -1;
    private ArrayList<SearchResultOther> otherlist ;
    private ArrayList<SearchResultCategory> categorylist;

    public FilterAdapter(Context context,
                         ArrayList<SearchResultOther> otherlist,
                         ArrayList<SearchResultCategory> categorylist) {
        this.context = context;
        this.otherlist = MyApplication.getInstance().getOtherlist();
        this.categorylist = MyApplication.getInstance().getCategorylist();
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return otherlist != null && otherlist.get(0)!=null ? otherlist.size() + 2 : 2;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final Holder4 holder = new Holder4();

        try {
            if (position == 0) {
                // 商品分类
                convertView = inflater.inflate(
                        R.layout.ouka_filter_listview_item, null);

                holder.titleTextView = (TextView) convertView
                        .findViewById(R.id.ouka_filter_item_title);
                holder.titleTextView.setText("分类");

                holder.imgImageView = (ImageView) convertView
                        .findViewById(R.id.ouka_filter_item_img);
                holder.itemGridView = (GridView) convertView
                        .findViewById(R.id.ouka_filter_item_gv);
                holder.titleAdapter = new FilterGridTitleAdapter(context,
                        categorylist);
                holder.itemGridView.setAdapter(holder.titleAdapter);

                // holder.imgImageView
                // .setBackgroundResource(R.drawable.ouka_filter_itemout);

                if (categorylist != null && categorylist.size() > position
                        && categorylist.get(position).getIsUnfold() != null
                        && categorylist.get(position).getIsUnfold()) {
                    holder.imgImageView
                            .setBackgroundResource(R.drawable.ouka_filter_itemin);
                    setListViewHeightBasedOnChildren(holder.itemGridView, 0);
                } else {
                    holder.imgImageView
                            .setBackgroundResource(R.drawable.ouka_filter_itemout);
                    setListViewHeightBasedOnChildren(holder.itemGridView, 1);
                }

                holder.itemGridView
                        .setOnItemClickListener(new OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> parent,
                                                    View view, int position, long id) {
                                holder.titleAdapter.chooceState(position);

                            }
                        });

                holder.titleLinearLayout = (LinearLayout) convertView
                        .findViewById(R.id.ouka_filter_item_ll);
                holder.titleLinearLayout
                        .setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                if (type == 1) {
                                    type = 0;
                                    // 展开
                                    if (MyApplication.getInstance()
                                            .getCategorylist() != null
                                            && MyApplication.getInstance()
                                            .getCategorylist().size() > position
                                            && MyApplication.getInstance()
                                            .getCategorylist()
                                            .get(position) != null) {
                                        MyApplication.getInstance()
                                                .getCategorylist()
                                                .get(position)
                                                .setIsUnfold(true);
                                    }
                                } else {
                                    type = 1;
                                    // 隐藏
                                    if (MyApplication.getInstance()
                                            .getCategorylist() != null
                                            && MyApplication.getInstance()
                                            .getCategorylist().size() > position
                                            && MyApplication.getInstance()
                                            .getCategorylist()
                                            .get(position) != null) {
                                        MyApplication.getInstance()
                                                .getCategorylist()
                                                .get(position)
                                                .setIsUnfold(false);
                                    }

                                }
                                if (MyApplication.getInstance()
                                        .getCategorylist() != null) {
                                    showTypeChange(holder.imgImageView,
                                            holder.itemGridView);
                                }
                            }
                        });

            } else if (position == 1) {
                // 商品价格区间
                convertView = inflater.inflate(
                        R.layout.ouka_filter_listview_price, null);
                holder.price_small = (EditText) convertView
                        .findViewById(R.id.price_small);
                holder.price_hight = (EditText) convertView
                        .findViewById(R.id.price_hight);
                holder.price_small.setTag(position);
                holder.price_hight.setTag(-1);
                holder.price_small.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            touchedPosition = position;
                        }
                        return false;
                    }
                });

                holder.price_hight.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            touchedPosition = -1;
                        }
                        return false;
                    }
                });

                class MyTextWatcher implements TextWatcher {
                    public MyTextWatcher(Holder4 holder) {
                        mHolder = holder;
                    }

                    private Holder4 mHolder;

                    @Override
                    public void onTextChanged(CharSequence s, int start,
                                              int before, int count) {
                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start,
                                                  int count, int after) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (s != null && !"".equals(s.toString())) {
                            int position = (Integer) mHolder.price_small
                                    .getTag();
                            MyApplication.getInstance().setPrice_small(
                                    s.toString());
                        } else {
                            MyApplication.getInstance().setPrice_small("");
                        }
                    }
                }
                class MyTextWatcherH implements TextWatcher {
                    public MyTextWatcherH(Holder4 holder) {
                        mHolder = holder;
                    }

                    private Holder4 mHolder;

                    @Override
                    public void onTextChanged(CharSequence s, int start,
                                              int before, int count) {
                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start,
                                                  int count, int after) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (s != null && !"".equals(s.toString())) {
                            int pos = (Integer) mHolder.price_hight.getTag();
                            // 当EditText数据发生改变的时候存到data变量中
                            MyApplication.getInstance().setPrice_hight(
                                    s.toString());
                        } else {
                            MyApplication.getInstance().setPrice_hight("");
                        }
                    }
                }

                holder.price_small.addTextChangedListener(new MyTextWatcher(
                        holder));
                holder.price_hight.addTextChangedListener(new MyTextWatcherH(
                        holder));

                holder.price_small.clearFocus();
                holder.price_hight.clearFocus();
                if (touchedPosition == position) {
                    // 如果当前的行下标和点击事件中保存的index一致，手动为EditText设置焦点。
                    holder.price_small.requestFocus();
                } else if (touchedPosition == -1) {
                    holder.price_hight.requestFocus();
                } else {
                    holder.price_small.clearFocus();
                    holder.price_hight.clearFocus();
                }
                holder.price_small.setText(MyApplication.getInstance()
                        .getPrice_small());
                holder.price_small.setSelection(holder.price_small.getText()
                        .length());
                holder.price_hight.setText(MyApplication.getInstance()
                        .getPrice_hight());
                holder.price_hight.setSelection(holder.price_hight.getText()
                        .length());

            } else {
                // 商品的各种属性
                convertView = inflater.inflate(
                        R.layout.ouka_filter_listview_item, null);
                holder.titleTextView = (TextView) convertView
                        .findViewById(R.id.ouka_filter_item_title);
                if (otherlist == null) {
                    return convertView;
                }
                final SearchResultOther resultOther = otherlist
                        .get(position - 2);
                if (resultOther == null) {
//					holder.titleTextView.setVisibility(View.GONE);
                    return convertView;
                }

                holder.titleTextView.setText(resultOther.getName());

                holder.itemGridView = (GridView) convertView
                        .findViewById(R.id.ouka_filter_item_gv);
                holder.adapter = new FilterGridAdapter(context,
                        resultOther.getItems());
                holder.itemGridView.setAdapter(holder.adapter);

                holder.imgImageView = (ImageView) convertView
                        .findViewById(R.id.ouka_filter_item_img);
                if (resultOther.getIsUnfold() != null
                        && resultOther.getIsUnfold()) {
                    holder.imgImageView
                            .setBackgroundResource(R.drawable.ouka_filter_itemin);
                    setListViewHeightBasedOnChildren(holder.itemGridView, 0);
                } else {
                    holder.imgImageView
                            .setBackgroundResource(R.drawable.ouka_filter_itemout);
                    setListViewHeightBasedOnChildren(holder.itemGridView, 1);
                }
                holder.itemGridView
                        .setOnItemClickListener(new OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> parent,
                                                    View view, int index, long id) {
                                boolean chooceState = holder.adapter
                                        .chooceState(position, index);
                                if (chooceState) {
                                    ToastUtils.showShort(context,
                                            "亲，最多只能选择5项哦！");
                                }
                                String newchar = "";
                                ArrayList<SearchResultOtherItems> items = resultOther
                                        .getItems();
                                String name = items.get(index).getName();
                                attr = PreferenceUtils.getInstance()
                                        .getSettingStr(
                                                PreferencesConfig.SEARCH_SATTR,
                                                "");
                                if (!MyApplication.getInstance().getOtherlist()
                                        .get(position - 2).getItems()
                                        .get(index).isSelect()) {

                                    String[] st = attr.split(",");
                                    attr = "";
                                    for (int i = 0; st != null && i < st.length; i++) {
                                        if (st[i].contains(name.split("/")[0])) {
                                            int leth = st[i].length();
                                            int indexs = st[i].indexOf(name);
                                            if ((name.length() + indexs) == leth) {
                                                if (indexs == 0) {
                                                    st[i] = st[i].replace(name,
                                                            "");
                                                } else {
                                                    String subsh = st[i]
                                                            .substring(
                                                                    indexs - 1,
                                                                    indexs);
                                                    if (subsh.equals("|")) {
                                                        st[i] = st[i].replace(
                                                                "|" + name, "");
                                                    } else {
                                                        st[i] = st[i].replace(
                                                                name, "");
                                                    }
                                                }

                                            } else {
                                                String subs = st[i].substring(
                                                        name.length() + indexs,
                                                        name.length() + indexs
                                                                + 1);
                                                if (subs.equals("|")) {
                                                    st[i] = st[i].replace(name
                                                            + "|", "");
                                                } else {
                                                    st[i] = st[i].replace(name,
                                                            "");
                                                }
                                            }
                                        }

                                        if (st != null && i == st.length - 1) {
                                            attr += st[i];
                                        } else {
                                            if (st[i].equals("")) {

                                            } else {
                                                attr += st[i] + ",";
                                            }
                                        }
                                    }

                                } else {
                                    String[] taskbian = name.split("/");
                                    if (attr.contains(taskbian[0])) {
                                        String[] namebiao = attr.split(",");
                                        for (int i = 0; namebiao != null
                                                && i < namebiao.length; i++) {
                                            if (namebiao[i]
                                                    .contains(taskbian[0])) {
                                                newchar = namebiao[i]
                                                        + "|"
                                                        + resultOther
                                                        .getItems()
                                                        .get(index)
                                                        .getName();
                                                attr = attr.replace(
                                                        namebiao[i], newchar);
                                            }
                                        }
                                    } else {
                                        if (attr != null && attr.length() > 0) {
                                            attr += ","
                                                    + resultOther.getItems()
                                                    .get(index)
                                                    .getName();
                                        } else {
                                            attr += resultOther.getItems()
                                                    .get(index).getName();
                                        }
                                    }
                                }
                                PreferenceUtils.getInstance().SetSettingString(
                                        PreferencesConfig.SEARCH_SATTR, attr);
                            }
                        });

                holder.titleLinearLayout = (LinearLayout) convertView
                        .findViewById(R.id.ouka_filter_item_ll);
                holder.titleLinearLayout
                        .setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                if (type == 1) {
                                    type = 0;
                                    // 展开
                                    if (MyApplication.getInstance()
                                            .getOtherlist() != null) {
                                        MyApplication.getInstance()
                                                .getOtherlist()
                                                .get(position - 2)
                                                .setIsUnfold(true);
                                    }
                                } else {
                                    type = 1;
                                    // 隐藏
                                    if (MyApplication.getInstance()
                                            .getOtherlist() != null) {
                                        MyApplication.getInstance()
                                                .getOtherlist()
                                                .get(position - 2)
                                                .setIsUnfold(false);
                                    }
                                }
                                if (MyApplication.getInstance().getOtherlist() != null) {
                                    showTypeChange(holder.imgImageView,
                                            holder.itemGridView);
                                }
                            }
                        });

            }
            if (convertView.getTag() == null) {
                convertView.setTag(holder);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return convertView;
    }

    public void showTypeChange(ImageView imgImageView, GridView itemGridView) {
        switch (type) {
            case 1:
                // 隐藏
                imgImageView.setBackgroundResource(R.drawable.ouka_filter_itemout);
                setListViewHeightBasedOnChildren(itemGridView, type);
                break;

            case 0:
                // 展开
                imgImageView.setBackgroundResource(R.drawable.ouka_filter_itemin);
                setListViewHeightBasedOnChildren(itemGridView, type);
                break;
        }
    }

    /**
     * 动态获取gridView的总高度
     *
     * @param listView
     *            girdView对象
     * @param type2
     */
    public void setListViewHeightBasedOnChildren(GridView listView, int type2) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 3;// listView.getNumColumns();
        int totalHeight = 0;
        int countLength = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        if (type2 == 1) {
            if (listAdapter.getCount() < 6) {
                countLength = listAdapter.getCount();
            } else {
                countLength = 6;
            }
        } else if (type2 == 0) {
            countLength = listAdapter.getCount();
        }
        for (int i = 0; i < countLength; i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
            // totalHeight += 12;
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((MarginLayoutParams) params).setMargins(7, 7, 7, 7);
        // 设置参数
        listView.setLayoutParams(params);
    }

}

class Holder4 {

    public EditText price_hight;
    public EditText price_small;
    TextView titleTextView;
    GridView itemGridView;
    FilterGridAdapter adapter;
    FilterGridTitleAdapter titleAdapter;
    LinearLayout titleLinearLayout;
    ImageView imgImageView;
}
